/**
 * Created by Dalyn on 2017/6/2.
 */
/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import { hashHistory } from 'react-router';
import Confirm from '../../../common/Confirm';
import Relay from "react-relay";
import ListOrderMutation from "../mutation/ListOrderMutation";
import Check from '../Check';
import Order_Item from './Order_Item';
import Util from "../../../util/Util"
import Pagination from "../Pagination";
import Reactkey from "../../../util/ReactKey";
import OrderPurch_Item from "./OrderPurch_Item";
import "./css/Order_OrderPurch_item.css";
import Modal_PayFor from "./Modal_PayFor";
import { message } from 'antd';
import Modal_Supplement  from "./Modal_Supplement"
import FinishOrderMutation from "../mutation/FinishOrderMutation"
/*信息列表*/
export default class ListOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            orders:[],
            totalresult:0,
            placeholder:'请输入企业名称进行搜索'

        };
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.permissionId = sessionStorage.getItem('permissionId');
        this.uid = sessionStorage.getItem('uid');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.odtail='1';
        this.ods='1,2,3,4';
        this.odsobj={0:'待发布',1:'已发布',3:'已签订',4:'已完成'};
        this.oddstatus=["全部:1,2,3,4","已发布:1,2","已签订:3","已完成:4"];
        this.enid = sessionStorage.getItem('enterpriseId');

        this.order_purch_oid = '';
        this.order_purch_account = '';
        this.order_purch_status = '';
        this.order_purch_type = '';

    }


    componentWillMount(){
        this.queryorderlist(10,1);
    }
    componentDidMount(){
        this.refs['df'+0].chose();
    }


    queryorderlist(pageSize,pageNum,enName){
        let orderType = '';
        if(this.serviceType ==1){
            orderType = '2,3'
        }else if(this.serviceType ==2){
            orderType = '2'
        }else if(this.serviceType ==3){
            orderType = '4,5'
        }else if(this.serviceType ==4){
            orderType = '4'
        }else if(this.serviceType ==5){
            orderType = '5'
        }else if(this.serviceType ==6){
            orderType = '1'
        }
        this.order_purch_oid = '';
        Relay.Store.commitUpdate(
            new ListOrderMutation({
                pageSize: pageSize,
                pageNum: pageNum,
                status:this.ods,
                type:'2',
                enId:this.enid,
                enName:enName||'',
                searchType:2,
                orderType:orderType
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.listOrder.listOrder.errorCode;
                    if(errorCode=='0'){
                        let orders = response.listOrder.listOrder.orders
                        let totalResult = response.listOrder.listOrder.totalResult
                        this.setState({
                            orders:orders,
                            totalresult:totalResult
                        });
                    }
                }
            }
        )
    }

    handleclick(){

    }


    choseoddetail(indexd,value){
        this.odtail = value
        this.oddetail.map((context,index)=>{
            if(indexd!=index){
                this.refs['de'+index].unchose();
            }
        });
        this.queryorderlist(10,1);
        this.refs.pagination.setState({
            text:1
        });
    }

    choseodorderstatus(indexd,value){
        this.ods = value;
        this.oddstatus.map((context,index)=>{
            if(indexd!=index){
                this.refs['df'+index].unchose();
            }
        });
        this.queryorderlist(10,1);
        this.refs.pagination.setState({
            text:1
        });
    }


    addorderstatus(){
        return this.oddstatus.map((con,index)=>{
            return(
                <Order_Item choseodstate={this.choseodorderstatus.bind(this)} key={index+'_'} ref={'df'+index} index={index} con={con}/>
            )

        })
    }


    check(){
        this.refs.check.setState({
            visible : true
        })
    }

    reloadList(){
        this.queryorderlist(10,1);
    }



    addDepartmenlist(){
        return this.state.orders.map((context,index)=>{
            let date = Util.dateFormat(context.createDate);
            let ods=this.odsobj[context.status];
            return (
                <OrderPurch_Item context={context} key = {Reactkey.key} index={index} _onChangeBoxCallBack = {this._onChangeBoxCallBack.bind(this)}
                                 ref={'order_item'+index} reloadList={this.reloadList.bind(this)}/>
            );
        });
    }

    _onChangeBoxCallBack(chooseindex,oid,account,check,status,type){
        if(check){
            this.order_purch_oid = oid;
            this.order_purch_account = account;
            this.order_purch_status = status;
            this.order_purch_type = type
        }else{
            this.order_purch_oid = '';
            this.order_purch_account = '';
            this.order_purch_status = '';
            this.order_purch_type = '';
        }
        this.state.orders.map((context,index)=>{
            if(chooseindex != index){
                this.refs['order_item'+index]._onChangeBoxFalse();
            }
        });
    }

    stroke(){

    }

    status(){
        return this.oArr.map((item,index)=>{
            return (
                <span style={{width:80,height:27,borderRadius:"8px",background:"#ccc",display:"block"}} onClick={this.stroke.bind(this)}>{item}</span>
            )
        })
    }

    createorder(){
        hashHistory.push('/createorder')
    }

    onSure(size,num){
        this.queryorderlist(size,num);
    }

    onfocusInput(){
        this.setState({
            placeholder:''
        })
    }


    bluronInput(){
        this.setState({
            placeholder:'请输入企业名称进行搜索'
        })

    }

    _PayFor(){
        message.config({
            top: 70,
            duration: 1.5,
        });
        if(this.order_purch_oid == ''){
            message.info('请选择订单');
            return;
        }
        if(this.order_purch_status == 4){
            message.info('交易已完成');
            return;
        }
        if(this.order_purch_status == 0){
            message.info('订单还未发布');
            return;
        }

        if(this.order_purch_status == 1){
            message.info('订单还未接收');
            return;
        }

        this.refs.modal_payfor.setState({
            visible:true,
            oid:this.order_purch_oid,
            account:this.order_purch_account
        });
    }
    _Supplement(){
        message.config({
            top: 70,
            duration: 1.5,
        });

        if(this.order_purch_oid == ''){
            message.info('请选择订单');
            return;
        }
        if(this.order_purch_status == 4){
            message.info('交易已完成');
            return;
        }
        if(this.order_purch_status == 0){
            message.info('订单还未发布');
            return;
        }

        if(this.order_purch_status == 1){
            message.info('订单还未接收');
            return;
        }

        // this.refs.modal_supplement.setState({
        //     visible:true,
        //     oid:this.order_purch_oid,
        //     account:this.order_purch_account
        // });

        let oid = this.order_purch_oid;


        switch (this.order_purch_type){
            case 0:

                return;
            case 1:
                hashHistory.push('/orderdetailgms/'+oid);
                // hashHistory.push({pathname:'/orderdetailgms/',state:{'oid':oid}})
                return;
            case 2:
                hashHistory.push('/orderdetailraw/'+oid);
                // hashHistory.push({pathname:'/orderdetailraw/',state:{'oid':oid}})
                return;
            case 3:
                hashHistory.push('/orderdetailcloth/'+oid);
                // hashHistory.push({pathname:'/orderdetailcloth/',state:{'oid':oid}})
                return;
            case 4:
                hashHistory.push('/orderdetailprint/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;
            case 5:
                hashHistory.push('/orderdetailyarn/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;

        }


    }

    _DealFinished(){
        message.config({
            top: 70,
            duration: 1.5,
        });
        if(this.order_purch_oid == ''){
            message.info('请选择订单');
            return;
        }
        if(this.order_purch_status == 4){
            message.info('交易已完成');
            return;
        }
        if(this.order_purch_status == 0){
            message.info('订单还未发布');
            return;
        }

        if(this.order_purch_status == 1){
            message.info('订单还未接收');
            return;
        }

        Relay.Store.commitUpdate(
            new FinishOrderMutation({
                orderId:this.order_purch_oid,
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.finishOrder.finishOrder.errorCode;
                    let value  = response.finishOrder.finishOrder.value;
                    if(errorCode==0){
                        message.success('交易成功');
                        let _pageNum = this.refs.pagination.state.text
                        this.queryorderlist(10, _pageNum);
                        this.setState({
                            visible:false
                        });
                    }else{
                        message.info('交易金额不符，请填写合同补充');
                    }
                }
            }
        )

    }

    _SearchByEn(){
        let enName = this.refs.enName.value
        this.queryorderlist(10,1,enName);
    }

    render(){
        return (
            <div className="order_box" style={{width:1233,minHeight:800,background:"#ffffff",marginTop:"10px",paddingTop:"10px"}}>
                <p style={{height:28,marginTop:"20px",}} >
                    <span style={{display:"block",float:"left",marginLeft:"20px",paddingRight:"15px",eight:28,lineHeight:"28px",fontSize:"14px",fontFamily:"Microsoft Yahei"}}>订单状态：</span>
                    {
                        this.addorderstatus()
                    }
                </p>
                <div className="order_saleandre_frome_search_box">
                    <input className="order_saleandre_frome_search_input" placeholder={this.state.placeholder}
                           onFocus={this.onfocusInput.bind(this)}
                           onBlur={this.bluronInput.bind(this)} ref={'enName'}/>
                    <span className="order_saleandre_frome_search_div" onClick={this._SearchByEn.bind(this)}>搜索</span>
                </div>
                <div className="order_saleandre_frome_button_box clear">
                    <p className="order_saleandre_frome_button_boxp">
                        <span className="order_orderpurch_item_titles order_orderpurch_item_titles3" onClick={this._PayFor.bind(this)}>申请付款</span>
                        <span className="order_orderpurch_item_titles order_orderpurch_item_titles2" onClick={this._Supplement.bind(this)}>补充合同</span>
                        <span className="order_orderpurch_item_titles order_orderpurch_item_titles3" onClick={this._DealFinished.bind(this)}>完成交易</span>
                    </p>

                </div>
                <div style={{width:1190,height:"560px",background:"#fff",margin:"0 auto",padding:"0 19px 0 19px",position:"relative"}}>
                    <table className="order_orderpurch_item_form_table">
                        <thead>
                        <tr className="order_orderpurch_item_from_tr">
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_check"/>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_oidtital">订单编号</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_partb">乙方</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_product">商品</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_count">数量</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_count">剩余数量</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_money">订单金额（元）</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_money">已支付金额（元）</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_doit">操作</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_end">收货记录</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_end">订单进度</td>
                            <td className="order_orderpurch_item_from_thd order_orderpurch_item_from_td_end">订单详情</td>
                        </tr>
                        </thead>

                        {
                            this.addDepartmenlist()
                        }

                    </table>
                    <Check ref={"check"}/>
                    <Pagination eachSize={10} dataSize={this.state.totalresult} onSure={this.onSure.bind(this)} ref={'pagination'}/>
                </div>
                <Modal_PayFor ref={'modal_payfor'} uid={this.uid}/>
                <Modal_Supplement ref={'modal_supplement'} uid={this.uid}/>
            </div>

        )
    }
}
